﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace SQLServerDAL
{
    public class UserInfo:IDAL.IUserInfo
    {
        /// <summary>
        /// 通过用户名查询用户
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户对象</returns>
        public Model.UserInfo GetUserInfoByUserName(string username) {
            string sql = "select * from userinfo where username=@UserName";
            SqlParameter[] pars = { 
                                    new SqlParameter("@UserName",username)
                                  };
            IList<Model.UserInfo> list = GetUserInfo(SqlHelp.ExecuteReader(sql, pars));
            return list.Count == 1 ? list[0] : null;
        }
        /// <summary>
        /// 通过用户编号查询用户
        /// </summary>
        /// <param name="uid">用户名</param>
        /// <returns>用户对象</returns>
        public Model.UserInfo GetUserInfoByUID(int uid) {
            string sql = "select * from userinfo where uid=@UID";
            SqlParameter[] pars = { 
                                    new SqlParameter("@UID",uid)
                                  };
            IList<Model.UserInfo> list = GetUserInfo(SqlHelp.ExecuteReader(sql, pars));
            return list.Count == 1 ? list[0] : null;
        }

        private IList<Model.UserInfo> GetUserInfo(SqlDataReader dr) {
            IList<Model.UserInfo> list = new List<Model.UserInfo>();
            while(dr.Read()){
                Model.UserInfo ui = new Model.UserInfo();
                ui.UID = dr.GetInt32(0);
                ui.UserName = dr.GetString(1);
                ui.Password = dr.GetString(2);
                list.Add(ui);
            }
            return list;
        }
    }
}
